
//
//  WeekDayCollectionViewLayout.m
//  TableTest
//
//  Created by 众拳科技 on 2017/11/13.
//  Copyright © 2017年 众拳科技. All rights reserved.
//


#import "WeekDayCollectionViewLayout.h"

@implementation WeekDayCollectionViewLayout

//初始化方法
- (void)prepareLayout{
    
    [super prepareLayout];
    
    self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    //设置cell之间间距
    self.minimumInteritemSpacing = 0;
    //设置行距
    self.minimumLineSpacing = 0;
    
    CGFloat itemWith = kScreenWidth / 8;
    
    //设置Item大小
    self.itemSize = CGSizeMake(itemWith, itemWith + 20);
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    NSMutableArray* attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    
    //从第2个循环到最后一个
    for(int i = 1; i < [attributes count]; ++i) {
        
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        
        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
        //设置最大间距，可根据需要改
        NSInteger maximumSpacing = 0;
        
        NSInteger maxX = CGRectGetMaxX(prevLayoutAttributes.frame);
        
        int col_idx = i % 8;
        
        float W = kScreenWidth / 8;
        
        //如果当前一个cell的最右边加上我们想要的间距加上当前cell的宽度依然在contentSize中，我们改变当前cell的原点位置
        //不加这个判断的后果是，UICollectionView只显示一行，原因是下面所有cell的x值都被加到第一行最后一个元素的后面了
        if(maxX + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
            
            CGRect frame = currentLayoutAttributes.frame;
            
            frame.origin.x = col_idx * W;
            
            currentLayoutAttributes.frame = frame;
        }
    }
    
    return attributes;
}

//是否实时刷新布局
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    
    return true;
}

@end
